package com.trumeen.immichgallery.network

import com.google.gson.GsonBuilder
import com.trumeen.immichgallery.repository.AuthManager
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {
    private var authManager: AuthManager? = null
    var baseUrl: String = "http://192.168.3.18:2283/api/"

    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    private val authInterceptor = Interceptor { chain ->
        val originalRequest = chain.request()

        val token = runCatching {
            runBlocking {
                authManager?.getAccessToken()
            }
        }.getOrNull()

        val request = if (!token.isNullOrBlank()) {
            originalRequest.newBuilder()
                .header("Authorization", "Bearer $token")
                .build()
        } else {
            originalRequest
        }

        chain.proceed(request)
    }

    private fun createOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(authInterceptor)
            .addInterceptor(loggingInterceptor)
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
    }

    fun initialize(manager: AuthManager) {
        authManager = manager
    }

    val apiService: ImmichService by lazy {
        createApiService(baseUrl)
    }

    fun createApiService(serverUrl: String): ImmichService {
        val formattedUrl = if (serverUrl.endsWith("/")) serverUrl else "$serverUrl/"

        val gson = GsonBuilder()
            .setLenient()
            .create()

        return Retrofit.Builder()
            .baseUrl(formattedUrl)
            .client(createOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(ImmichService::class.java)
    }

    fun updateBaseUrl(newUrl: String) {
        baseUrl = newUrl
    }
}